/*
 * SocialRewardResource.cpp
 *
 *  Created on: 2013. 9. 6.
 *      Author: mega@gamevil.com
 */

#include "../User.h"
#include "SocialRewardResource.h"
#include "../NUtil/Utils.h"
#include "../engine.h"

namespace ProjectZ { namespace NResource {

SocialRewardResource::SocialRewardResource()
{
	pSocialRewardAndroid	= new SocialRewardData;
	pSocialRewardIOS		= new SocialRewardData;
}

SocialRewardResource::~SocialRewardResource()
{
	delete pSocialRewardAndroid;
	delete pSocialRewardIOS;
}

bool SocialRewardResource::LoadResource()
{
	if (false == pSocialRewardAndroid->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE))
		return false;

	if (false == pSocialRewardIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS))
		return false;

	return true;
}

SocialRewardData::Flyweight * SocialRewardResource::GetFly(User * pUser, int seq)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(pUser->GetCompany(), pUser->GetSaleCode());

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pSocialRewardAndroid->GetFly(seq);

	case NUtil::MarketType::IOS_KAKAO:
		return pSocialRewardIOS->GetFly(seq);

	default:
		return NULL;
	}

	return NULL;
}


SocialRewardData::~SocialRewardData()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
}

void
SocialRewardData::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
	clsFlyTree.clear();
}

bool SocialRewardData::LoadResource(int company, int saleCode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT NATIONAL_CODE, seq, send_reward, receive_reward, message_type, magnification FROM resource_social_reward WHERE company=%d AND sale_cd=%d", company, saleCode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		SocialRewardData::Flyweight * pFly = new SocialRewardData::Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_SEQ >> pFly->_SEND_REWARD >> pFly->_RECV_REWARD >> pFly->_MSG_TYPE >> pFly->_IS_EVENT;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_SEQ] = pFly;
	}

	return true;
}

SocialRewardData::Flyweight * SocialRewardData::GetFly(int seq)
{
	auto iter = clsFlyTree.find(seq);

	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

} /* NResource */ } /* ProjectZ */
